package com.hrt.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hrt.bean.GiftInfor;
import com.hrt.bean.ProductInfor;


public abstract class BaseDaoImpl<E> extends HibernateDaoSupport implements BaseDao<E> {
	

	@SuppressWarnings("unused")
	private SessionFactory sessionFactory;
	
	/**
	 * 根据条件进行查询，方法需要重写，自由实现业务
	 * @param conditions
	 * @return
	 */
	public  List<E> queryByCondition(List conditions){
		
		return null;
		
	}
	
	@Override
	public List<E> loadList(Class<E> clzz) {
		final String hql="from "+clazz.getSimpleName()+" as a where a.isdelete=:isdelete";
		List<E> list=this.getHibernateTemplate().executeFind(new HibernateCallback<E>(){
			/*String hql=	"FROM "+ clazz.getSimpleName() + " as a where a.id in(:ids) and a.isdelete=:isdelete";*/
			@Override
			public E doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				
				query.setInteger("isdelete", 0);
				return (E) query.list();
	}
		});
		return list;
	}

	/**
	 * 根据条件进行分页查询，方法需要重写，自由实现业务
	 * @param conditions
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public  List<E>  queryPageByCondition(List conditions,int pageIndex,int pageSize) {
		
		return null;
	}
	
	@Override
	@Autowired  
    public void setSessionFactoryOverride(SessionFactory sessionFactory)   
    {   
  
        super.setSessionFactory(sessionFactory);   
    } 


	protected Class<E> clazz;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public BaseDaoImpl() {
		//通过反射得到E的类型
		ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
		this.clazz = (Class<E>) pt.getActualTypeArguments()[0];
	}
	
	
	/**
	 * 
	 * @param clz
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public Long totalCount() {
		final String hql="select count(*) from "+clazz.getSimpleName()+" as a where a.isdelete=:isdelete";
		List<E> list=this.getHibernateTemplate().executeFind(new HibernateCallback<E>(){
			/*String hql=	"FROM "+ clazz.getSimpleName() + " as a where a.id in(:ids) and a.isdelete=:isdelete";*/
			@Override
			public E doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				
				query.setInteger("isdelete", 0);
				return (E) query.list();
	}
		});
		return new Long(list.get(0).toString());
	}

	/**
	 * 保存实体
	 * */
	@Override
	
	public Long saveEntity(E entity) {
		try{
		Serializable seriable=this.getSession().save(entity);
		return new Long(seriable.toString());
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return -1l;
		
		
	}

	/**
	 * 更新实体
	 * @return 
	 * */
	@Override
	public void updateEntity(E entity){
		/*getSession().update(entity);*/
		try{
		getHibernateTemplate().update(entity);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
	}
	@Override
	public void saveOrUpdateEntity(E entity) {
		try{
			getHibernateTemplate().saveOrUpdate(entity);
			}catch(Exception e)
			{
				e.printStackTrace();
			}
	}

	/**
	 * 删除实体
	 * */
	

	/**
	 * 按id查询实体
	 * */
	@Override
	public E getById(Long id) {
		return getHibernateTemplate().get(clazz, id);
	}

	/**
	 * 按id列表查询实体
	 * */
	@SuppressWarnings({ "deprecation", "unchecked" })
	@Override
	public List<E> getByIds(final Long[] ids) {
		if(ids == null || ids.length == 0) {
			return Collections.EMPTY_LIST;
		}
		
		
		List<E> list=this.getHibernateTemplate().executeFind(new HibernateCallback<E>(){
			String hql=	"FROM "+ clazz.getSimpleName() + " as a where a.id in(:ids) and a.isdelete=:isdelete";
			@Override
			public E doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				query.setParameterList("ids", ids);
				query.setInteger("isdelete", 0);
				return (E) query.list();
	}
		});
		return list;
	}

	/**
	 * 查询所有
	 * */
	@Override
	public void deleteEntity(Long id) {
		try{
		Object obj = getHibernateTemplate().get(clazz,id);
		getHibernateTemplate().delete(obj);
		}catch(Exception e)
		{
			
		}
		
	}
	

	/* (non-Javadoc)
	 * @see com.hrt.util.ISuperDao#queryByPage(java.lang.Class, int, int)
	 */
	@SuppressWarnings("deprecation")
	@Override
	public List<E> queryByPage(final int pageIndex, final int pageSize)  {
		
	
		@SuppressWarnings("unchecked")
		List<E> list=this.getHibernateTemplate().executeFind(new HibernateCallback<E>(){
			String hql="from "+clazz.getSimpleName()+" as a where a.isdelete=:isdelete";
			@Override
			public E doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				query.setInteger("isdelete", 0);
				query.setFirstResult((pageIndex-1)*pageSize);
				query.setMaxResults(pageSize);
				List<?> result=query.list();
				return  (E) result;
			}
			
			

		});
		return list;
	
}
	
	public List<E> queryByPage(final String hql,final int pageIndex, final int pageSize)  {
		
		
		@SuppressWarnings({ "unchecked", "deprecation" })
		List<E> list=this.getHibernateTemplate().executeFind(new HibernateCallback<E>(){
			
			@Override
			public E doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
//				query.setInteger("isdelete", 0);
				query.setFirstResult((pageIndex-1)*pageSize);
				query.setMaxResults(pageSize);
				List<?> result=query.list();
				return  (E) result;
			}
			
			

		});
		return list;
	
}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findAll() {
		
		return (List<E>) this.getHibernateTemplate().loadAll(clazz);
	}
	
	/**获取数据库的当前Timestamp形式的时间*/
	@SuppressWarnings("deprecation")
	public Timestamp getDate(){
		/*Date ss= (Date) getSession().createQuery("SELECT NOW()");
		System.out.println(ss);*/
		Session session = this.getSession();
        Query query = session.createSQLQuery("select now() ");
		return  (Timestamp)query.uniqueResult();
	}
	
	
	public E loadById(Class<E> clzz, Long id) {
		
		System.out.println(clzz.getName());
		System.out.println(id);
		return getHibernateTemplate().load(clzz,id);
	}
	

	
	@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
	public List<E> getEntityList(Class class1, String propertyName,Long propertyValue) {
		
		System.out.println(class1.getName());
		final String hql="select  c from "+class1.getSimpleName()+" c where c."+propertyName+"="+propertyValue;
		return getHibernateTemplate().executeFind(new HibernateCallback<E>(){

			@Override
			public E doInHibernate(final Session session) throws HibernateException,
					SQLException {
				final Query query=session.createQuery(hql);
				return (E) query.list();
			}
			
		});
	}
	
}
